package com.banmao.CarlCamp.Day07;

import java.util.ArrayDeque;

/**
 * https://leetcode.cn/problems/reverse-words-in-a-string/
 */
public class LC151 {

    public String reverseWords(String s) {
        ArrayDeque<String> strs = new ArrayDeque<>();

        char[] chars = s.toCharArray();
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i <= chars.length; i++) {
            if (i == chars.length || Character.isWhitespace(chars[i])) {
                if (sb.length() > 0) {
                    strs.add(sb.toString());
                }
                sb = new StringBuilder();
            } else {
                sb.append(chars[i]);
            }
        }

        sb = new StringBuilder();
        while (!strs.isEmpty()) {
            String pop = strs.pollLast();
            if (pop.length() == 0) {
                continue;
            }
            sb.append(pop);
            if (!strs.isEmpty()) {
                sb.append(" ");
            }
        }

        return sb.toString();
    }

    public static void main(String[] args) {
        LC151 lc151 = new LC151();
        String res = lc151.reverseWords(" hello world ");
        System.out.println(res);
    }

}
